package org.ediba.siri.web;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ediba.siri.core.image.domain.Image;
import org.ediba.siri.core.image.service.ImageService;
import org.springframework.web.servlet.view.AbstractView;

public class ImagesPackedView extends AbstractView {

	private ImageService imageService;
	public void setImageService(ImageService imageService) {this.imageService = imageService;}
	
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		@SuppressWarnings("unchecked")
		List<Image> images = (List<Image>) model.get("data");
		Integer[] _ids = new Integer[images.size()];
		int i = 0;
		for (Image image : images)
			_ids[i++] = image.getId();
				
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + new SimpleDateFormat("yyyy_MM_dd").format(Calendar.getInstance().getTime()) + ".zip\"");
        ZipOutputStream zipOutputStream = null;
		try {zipOutputStream = new ZipOutputStream(response.getOutputStream());
		} catch (IOException e1) {e1.printStackTrace();}
        byte bytes[] = new byte[4096];
        int bytesRead = 0;
        BufferedInputStream bufferedInputStream;
        InputStream inputStream;
        String type;
        Image image;
		
		for (Integer _id : _ids) {
			image = this.imageService.retrieve(_id);
			for (Map.Entry<String,InputStream> master : this.imageService.retrieveMaster(_id).entrySet()) {
				inputStream = master.getValue();
				type = master.getKey();
				bufferedInputStream = new BufferedInputStream(inputStream);
	            try {
	            	zipOutputStream.putNextEntry(new ZipEntry(image.getName() + "." + type));
		            bytesRead = 0;
		            while ((bytesRead = bufferedInputStream.read(bytes)) != -1) {
		            	zipOutputStream.write(bytes, 0, bytesRead);
		            }
		            zipOutputStream.closeEntry();
		            bufferedInputStream.close();
		            inputStream.close();
				} catch (IOException e) {e.printStackTrace();}
			}
		}
		try {
			zipOutputStream.flush();
			zipOutputStream.finish();
		} catch (IOException e1) {e1.printStackTrace();}
	
		

	}

}
